const ajax = userOptions => {
    return new Promise((resolve, reject) => {
        //  默认配置项
        const DEFAULT = {
            url: "",
            method: "",
            data: {},
            type: '',
            headers:{
                token:''
            }
        };

        //  先与用户合并，再通过解构赋值，拿到需要的参数
        const { url, method, data, type, headers} = Object.assign({}, DEFAULT, userOptions);
        const xhr = new XMLHttpRequest();
        //  判断请求方式，决定发送数据的行为
        if (method.toUpperCase() === "GET") {
            let newUrl = url + '?';
            for (let k in data) {
                newUrl += `${k}=${data[k]}&`;
            };
            newUrl = newUrl.slice(0, -1);
            xhr.open("GET", newUrl, true);
            xhr.setRequestHeader("x-token",headers.token)
            xhr.send(null);
        } else {
            xhr.open(method, url, true);    
            //  判断发送格式是否为json
            if (type) {
                //  json
                xhr.setRequestHeader('Content-Type', 'application/json');
                xhr.setRequestHeader("x-token",headers.token)
                xhr.send(JSON.stringify(data));
            } else {
                //  application/x-www-form-urlencoded
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xhr.setRequestHeader("x-token",headers.token)
                let postData = "";
                for (let k in data) {
                    postData += `${k}=${data[k]}&`;
                };
                postData = postData.slice(0, -1);
                xhr.send(postData);

            }
        }

        xhr.addEventListener("readystatechange", () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    return resolve(JSON.parse(xhr.response));
                }else{
                    return reject(xhr.response)
                }
            }

        })
    })
}